<template>
  <div>
    <ElRow style="margin-bottom: 16px;" justify="end">
      <ElCol :span="15">
        <el-button v-if="hasPerms('question:create')" type="primary" @click="handleAddQuestion">新增</el-button>
      </ElCol>
      <div style="flex:1; display: flex;justify-content: flex-end;">
        <ElSelect v-model="selectType" placeholder="题目类型查询" clearable @change="handleSelectChange"
          style="width: 200px;margin-right: 16px;">
          <ElOption label="单选题" :value=1 />
          <ElOption label="多选题" :value="2" />
          <ElOption label="填空题" :value="3" />
        </ElSelect>
        <ElInput :prefix-icon="Search" v-model="searchNo" placeholder="试题编号查询" @change="handleSearchNoChange" clearable
          style="width: 200px;margin-right: 16px;" />
      </div>
    </ElRow>
    <ReTable :data="questionList" :columns="columns" :height="tableHeight" :pagination="pagination"
      @current-change="handleCurrentChange" @size-change="handleSizeChange">
      <template #type="{ row }">
        {{ QuestionType[row.type] }}
      </template>
      <template #action="{ row }">
        <ElRow justify="center" align="middle">
          <ElCol :span="6" v-if="hasPerms('question:edit')">
            <ElButton link type="primary" @click="handleEditQuestion(row)">
              编辑
            </ElButton>
          </ElCol>
          <ElCol :span="6" v-if="hasPerms('question:status')">
            <ElSwitch v-model="row.status" inline-prompt active-text="启用" inactive-text="禁用" :active-value="1"
              :inactive-value="0" @change="handleSwitchChange(row)">
            </ElSwitch>
          </ElCol>
        </ElRow>
      </template>
    </ReTable>
    <ElDialog :title="dialogTitle" v-model="dialogVisible" :close-on-click-modal="false" width="50%" destroy-on-close>
      <ElForm :model="form" :rules="rules" label-width="auto" ref="qformRef">
        <ElFormItem label="题型选择" prop="type">
          <ElSelect v-model="form.type" placeholder="请选择试题类型" @change="handleTypeChange">
            <ElOption label="单选题" :value="1" />
            <ElOption label="多选题" :value="2" />
            <ElOption label="填空题" :value="3" />
          </ElSelect>
        </ElFormItem>
        <Fragment v-if="!!form.type">
          <ElFormItem label="题干" prop="title">
            <ElInput v-model="form.title" type="textarea" :rows="5" />
          </ElFormItem>
          <ElFormItem label="题干图" prop="titleImage">
            <el-upload class="avatar-uploader" action="/api/platform/file/upload/image" v-model:file-list="avatarList"
              with-credentials :headers="{ token: getToken().token }" :multiple="true" list-type="picture-card"
              :limit="10" :on-preview="handlePictureCardPreview">
              <template #trigger>
                <el-icon class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </template>
            </el-upload>
          </ElFormItem>
        </Fragment>
        <ElFormItem v-if="form.type === 1 || form.type === 2" label="选项" prop="options">
          <ElTable :data="form.options" border>
            <ElTableColumn align="center" label="正确答案" prop="checked">
              <template #default="scope">
                <ElRadioGroup v-model="scope.row.checked" v-if="form.type === 1" @change="handleRadioChange(scope.row)">
                  <ElRadio :value="true" />
                </ElRadioGroup>
                <ElCheckbox v-if="form.type === 2" v-model="scope.row.checked" />
              </template>
            </ElTableColumn>
            <ElTableColumn align="center" label="选项" prop="key" />
            <ElTableColumn align="center" label="文案" prop="content">
              <template #default="scope">
                <ElInput v-model="scope.row.content" placeholder="请输入文案" />
              </template>
            </ElTableColumn>
            <ElTableColumn align="center" label="图片" prop="image">
              <template #default="scope">
                <ElUpload action="/api/platform/file/upload/image" :headers="{ token: getToken().token }"
                  :show-file-list="false" @success="handleAnwserUploadSuccess($event, scope.$index)">
                  <img v-if="scope.row.image" :src="scope.row.image" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </ElUpload>
              </template>
            </ElTableColumn>
          </ElTable>
        </ElFormItem>
        <ElFormItem v-if="form.type === 3" label="正确答案" prop="correctAnswer">
          <ElInput v-model="form.correctAnswer" placeholder="请输入正确答案" />
        </ElFormItem>
        <ElFormItem label="答案解析" prop="answerAnalysis">
          <ElInput v-model="form.answerAnalysis" placeholder="请输入答案解析" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <span class="dialog-footer">
          <ElButton @click="dialogVisible = false">取消</ElButton>
          <ElButton type="primary" @click="handleConfirm">确定</ElButton>
        </span>
      </template>
    </ElDialog>
    <el-dialog v-model="previewVisible" title="预览" width="50%">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { createQuestion, getQuestionDetail, getQuestions, QuestionType, updateQuestion, updateQuestionStatus } from '@/api/question';
import ReTable from '@/components/ReTable';
import { onMounted } from 'vue';
import { ref } from 'vue';
import { Plus, Search } from '@element-plus/icons-vue';
import { getToken, hasPerms } from '@/utils/auth';
import { ElMessage } from 'element-plus';
import { computed } from 'vue';

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "QuestionManage"
});
const tableHeight = computed(() => {
  return window.innerHeight - 300
})
const dialogImageUrl = ref('')
const previewVisible = ref(false)
// 控制弹窗显示隐藏
const dialogTitle = ref('新增试题')
const dialogVisible = ref(false)
const qformRef = ref()
// 试题列表
const questionList = ref([])
// 分页数据
const pagination = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
})
// 表单规则
const rules = {
  type: [
    { trigger: 'change', message: '请选择题型', required: true }
  ],
  title: [{ trigger: 'blur', message: '请输入题干', required: true }],
  correctAnswer: [
    {
      validator() { return form.value.correctAnswer.length > 0 }, message: '请选择正确答案', required: true
    }
  ],
  answerAnalysis: [{ trigger: 'blur', message: '请输入答案解析', required: true }]
}
const handlePictureCardPreview = (uploadFile: { url: string; }) => {
  dialogImageUrl.value = uploadFile.url!
  previewVisible.value = true
}
// 筛选条件题型
const selectType = ref('')
// 试题编号搜索
const searchNo = ref('')
// 试题表单
const form = ref<any>({
  type: null,
  title: '',
  titleImage: '',
  options: [
    {
      key: 'A',
      content: '',
      image: '',
      checked: false
    },
    {
      key: 'B',
      content: '',
      image: '',
      checked: false
    },
    {
      key: 'C',
      content: '',
      image: '',
      checked: false
    },
    {
      key: 'D',
      content: '',
      image: '',
      checked: false
    }
  ],
  correctAnswer: '',
  answerAnalysis: ''
})

// 表格列配置
const columns = [
  {
    label: '试题编号',
    prop: 'questionNo'
  },
  {
    label: '题型',
    slotName: 'type'
  },
  {
    label: '题干',
    prop: 'title'
  },
  {
    label: '创建时间',
    prop: 'gmtCreate'
  },
  {
    label: '创建人',
    prop: 'createBy'
  },
  {
    label: '操作',
    slotName: 'action'
  }
]

// 切换selectType
const handleSelectChange = (val: string) => {
  selectType.value = val
  queryQuestionList()
}

// 切换搜索试题编号
const handleSearchNoChange = (val: string) => {
  searchNo.value = val
  queryQuestionList()
}

// 切换分页
const handleCurrentChange = (val: number) => {
  pagination.value.pageNum = val
  queryQuestionList()
}

// 切换每页显示数量
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  queryQuestionList()
}

// 查询试题列表
const queryQuestionList = () => {
  getQuestions({
    pageNum: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
    type: selectType.value,
    questionNo: searchNo.value
  }).then(res => {
    questionList.value = res.data.records
    pagination.value.total = res.data.total
  })
}

// 切换单选
const handleRadioChange = (val: any) => {
  form.value.options.forEach((item: { key: any; checked: boolean; }) => {
    console.log(item.key == val.key)
    if (item.key == val.key) {
      item.checked = true
    } else {
      item.checked = false
    }
  })
  console.log(form.value.options)
}

// 新增试题
const handleAddQuestion = () => {
  initForm()
  dialogVisible.value = true
}

// 编辑试题
const handleEditQuestion = (row: any) => {
  dialogTitle.value = '编辑试题'
  initForm(row)
  getQuestionDetail(row.id).then(res => {
    if (res.code == 200) {
      if (row.type === 3) {
        form.value = {
          ...form.value,
          title: res.data.title,
          titleImage: res.data.titleImage, // 试题图片
          correctAnswer: res.data.correctAnswer,
          answerAnalysis: res.data.answerAnalysis,
        }
        avatarList.value = res.data.titleImage ? res.data.titleImage.split(',').map((item: any) => {
          return {
            url: item
          }
        }) : []
      } else {
        // 解析options字段和correctAnswer字段
        const options = JSON.parse(res.data.options).map((item: any) => {
          return {
            ...item,
            checked: row.type === 1 ? item.key == res.data.correctAnswer : res.data.correctAnswer.split(',').includes(item.key),
          }
        })
        form.value = {
          ...form.value,
          title: res.data.title,
          titleImage: res.data.titleImage, // 试题图片
          options: options,
          correctAnswer: res.data.correctAnswer,
          answerAnalysis: res.data.answerAnalysis,
        }
        avatarList.value = res.data.titleImage ? res.data.titleImage.split(',').map((item: any) => {
          return {
            url: item
          }
        }) : []
      }
      dialogVisible.value = true
    }
  })
}

// 上传图片成功
const avatarList = ref<any>([])
const handleAvatarSuccess = (res: any) => {
  console.log(res)
  avatarList.value.push({
    url: res.data,
  })
}

// 选项上传图片成功
const handleAnwserUploadSuccess = (res: any, index: number) => {
  form.value.options[index].image = res.data
}

const initForm = (row: any = {}) => {
  if (row.id) {
    form.value = {
      ...row,
    }
    console.log(form.value)
    return
  }
  avatarList.value = []
  form.value = {
    type: null,
    title: '',
    titleImage: '',
    options: [
      {
        key: 'A',
        content: '',
        image: '',
        checked: false
      },
      {
        key: 'B',
        content: '',
        image: '',
        checked: false
      },
      {
        key: 'C',
        content: '',
        image: '',
        checked: false
      },
      {
        key: 'D',
        content: '',
        image: '',
        checked: false
      }
    ],
    correctAnswer: '',
  }
}
// 记录上一次选择的题型
const lastType = ref(null)
// 切换题型
const handleTypeChange = (val: string) => {
  // 初始化表单
  initForm()
  form.value.type = val
}

/**
* 全角字符转换为半角字符
* @params str string 被转换的字符串
* @returns string 转换后的字符串
*/
const getString = (str: string) => {
  var result = ""; //替换后的结果 
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) == 12288) //全角空格 
      result += String.fromCharCode(32); //半角空格 
    else if (str.charCodeAt(i) > 65280 && str.charCodeAt(i) < 65375)
      result += String.fromCharCode(str.charCodeAt(i) - 65248); //其他全角字符 
    else
      result += String.fromCharCode(str.charCodeAt(i));
  }
  return result;
}

// 提交表单
const handleConfirm = () => {
  qformRef.value.validate((valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        form.value.correctAnswer = getString(form.value.correctAnswer)
        form.value.titleImage = avatarList.value.map((item: any) => item.response.data).join(',')
        updateQuestion(form.value.id, form.value).then(() => {
          ElMessage.success('修改成功')
          dialogVisible.value = false
          queryQuestionList()
        })
      } else {
        if (form.value.type !== 3) {
          // 拼接correctAnswer
          const correctAnswer = form.value.options.filter((item: { checked: any; }) => item.checked).map((item: { key: any; }) => item.key).join(',')
          form.value.correctAnswer = correctAnswer
        }
        form.value.correctAnswer = getString(form.value.correctAnswer)
        form.value.titleImage = avatarList.value.map((item: any) => item.response.data).join(',')
        createQuestion(form.value).then(() => {
          ElMessage.success('新增成功')
          dialogVisible.value = false
          queryQuestionList()
        })
      }
    }
  })
}

// 更新试题状态
const handleSwitchChange = (row: any) => {
  updateQuestionStatus(row.id, row.status).then((res) => {
    if (res.code === 200) {
      ElMessage.success('操作成功')
      queryQuestionList()
    }
  })
}

onMounted(() => {
  queryQuestionList()
})

</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--tw-ring-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload img {
  width: 100px;
  height: 100px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--tw-ring-color);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.el-dialog__body {
  min-height: 500px;
}
</style>